<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import ImgByIdVue from '@/components/imgbyfileid/index.vue'
import { ElMessage, ElUpload } from 'element-plus'
import { computed, ref, watch } from 'vue';
import { GeneralRespData } from '@/api';
import { PassCodeList } from '@/tools';
const envObj = import.meta.env
const event = defineEmits(['update:modelValue'])
interface Props {
  action?: string,
  modelValue?: string,
  title?: string
}
const props = withDefaults(defineProps<Props>(), {
  action: '/sysFileInfo/upload'
})
const imgLoading = ref(false)
const computedAction = computed(() => {
  return envObj.VITE_API_BASE + props.action
})
function handleAvatarSuccess(params: GeneralRespData<string>) {
  const { data, code, message } = params
  if (!PassCodeList.includes(code)) {
    return ElMessage.error(message)
  }
  const { modelValue } = props
  if (Array.isArray(modelValue)) {
    event('update:modelValue', [...modelValue, data])
  } else {
    event('update:modelValue', data)
  }
}
const headers = { token: sessionStorage.getItem('token') }
function handleComplite() {
  imgLoading.value = false
}
watch(() => props.modelValue, _ => {
  if (!_) return
  imgLoading.value = true
})
</script>

<template>
  <el-upload class="avatar-uploader" :headers="headers" v-loading="imgLoading" :action="computedAction"
    :on-success="handleAvatarSuccess" :show-file-list="false" v-bind="$attrs">
    <ImgByIdVue v-if="modelValue" class="avatar" @load="handleComplite" :fileid="modelValue" />
    <div v-else class="avatar-uploader-icon">
      <div class="triger-icon">
        <slot>
          <el-icon>
            <Plus />
          </el-icon>
        </slot>
      </div>
      <div v-if="Boolean(title)" class="customer-tip">
        <ElTag effect="plain">{{ title }}</ElTag>
      </div>
    </div>
  </el-upload>
</template>
<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
}

.avatar-uploader .triger-icon {
  width: 100%;
  flex-grow: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader .customer-tip {
  min-height: 2em;
}
</style>